package com.yisu.expressway.service_district;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.model.ServiceDistrictItem;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.settings.AppConfig;
import com.yisu.expressway.settings.AppConstant;
import com.yisu.expressway.settings.AppGlobalSetting;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ServiceDistrictListActivity extends BaseActivity {

    @Bind(R.id.bd_map_view)
    protected MapView mMapView;
    @Bind(R.id.rv_service_list)
    protected RecyclerView mRv_list;
    @Bind(R.id.tv_searching_notify)
    protected TextView mTv_seaching_notify;
    @Bind(R.id.tv_total_count)
    protected TextView mTv_totalCount;
    @Bind(R.id.btn_back)
    protected ImageButton mIv_backBtn;
    @Bind(R.id.id_divider)
    protected View mDididerLine;

    private LocationInfo locInfo;
    private BaiduMap mBaiduMap;
    private boolean isFromHome;
    private float autoEnterDistance = AppConstant.AUTO_ENTER_DISTRICT_DISTANCE;

    private final static String IS_FROM_HOME = "is_from_home";
    AppGlobalSetting sp ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_district_list);
        initView(getIntent());
    }

    private void initView(Intent intent){

        isFromHome = intent.getBooleanExtra(IS_FROM_HOME,false);
        sp = new AppGlobalSetting(this);
        autoEnterDistance = sp.getFloatGlobalItem(AppConfig.PREF_AUTO_ENTER_DISTANCE,0.03f);
        mRv_list.addItemDecoration(new DividerListItemDecoration(this, DividerListItemDecoration.VERTICAL_LIST));
        mRv_list.setLayoutManager(new LinearLayoutManager(this));
        getCurrentServiceDistrict();

    }

    public static void launch(Context context,boolean fromHome){
        Intent intent = new Intent(context,ServiceDistrictListActivity.class);
        intent.putExtra(IS_FROM_HOME,fromHome);
        context.startActivity(intent);
    }

    @OnClick (R.id.btn_back)
    public void onBackClick(){
        finish();
    }


    /**
     * 获取当前位置
     */
    private void getCurrentServiceDistrict(){
        showLoadingPage();
        showLoading();

        locInfo = LocationService.getInstance().getLocationResult();
        if(locInfo == null){
            LocationService.getInstance().start(new LocationListener() {
                @Override
                public void onSuccess(LocationInfo info) {
                    locInfo = info;
                    getNearByServiceDistric();
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    mTv_seaching_notify.setText(R.string.click_to_relocate_and_search);
                    ToastUtil.displayShortToastMsg(ServiceDistrictListActivity.this,errorMessage);
                }
            });
        }else{
            getNearByServiceDistric();
        }
    }

    private void showLoadingPage(){
        showUI(true);
        mTv_seaching_notify.setVisibility(View.GONE);
    }

    /**
     * 获取附近服务器列表
     */
    private void getNearByServiceDistric(){
//        mTitleBar.setTitle(R.string.is_searching_nearby_service_district);
        Map<String, Object> params = new HashMap();
        params.put("longitude", locInfo.getLongitude());
        params.put("latitude", locInfo.getLatitude());
        ApiClientHelper.postApi(ApiSetting.getNearByServiceDistrictList(), new TypeToken<ArrayList<ServiceDistrictItem>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<ArrayList<ServiceDistrictItem>>>() {
            @Override
            public void onResponse(ApiResult<ArrayList<ServiceDistrictItem>> result) {

                dismissLoading();

                if (!result.success) {
                    mTv_seaching_notify.setVisibility(View.VISIBLE);
                    mTv_seaching_notify.setText(R.string.click_to_relocate_and_search);
                    ToastUtil.displayLongToastMsg(ServiceDistrictListActivity.this, result.getMsg());
                    return;
                }

                ArrayList<ServiceDistrictItem> mList = result.getResult();
                if(mList == null || mList.size() == 0){
                    ToastUtil.displayShortToastMsg(ServiceDistrictListActivity.this,R.string.no_service_district_fount);
//                    mTitleBar.setTitle(R.string.no_service_district_fount);
                    return;
                }

                if(isFromHome){
                    showNearByServiceDistrictList(mList);
                    return;
                }

                ServiceDistrictItem autoEnterItem = getAutoEnterDistrict(mList);
                if(autoEnterItem != null){
                    DistrictDetailActivity.launch(ServiceDistrictListActivity.this,autoEnterItem);
                }else {
                    showNearByServiceDistrictList(mList);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissLoading();
                mTv_seaching_notify.setVisibility(View.VISIBLE);
                mTv_seaching_notify.setText(R.string.click_to_relocate_and_search);
                ToastUtil.displayShortToastMsg(ServiceDistrictListActivity.this, volleyError.getMessage());
            }
        }, this);
    }

    /**
     * 过滤最近服务区 若距离为30米之内，则自动进入详情页
     */
    public ServiceDistrictItem getAutoEnterDistrict(ArrayList<ServiceDistrictItem> districtList){
        ServiceDistrictItem autoItem = null;

        for(ServiceDistrictItem distirct :  districtList){
            if(distirct.distance <= autoEnterDistance){
                autoItem = distirct;
                break;
            }
        }

        return autoItem;

    }

    /**
     * 显示服务区列表
     */
    private void showNearByServiceDistrictList(ArrayList<ServiceDistrictItem> list){
        showUI(false);
//        mTitleBar.setTitle(R.string.choose_service_district);
        mRv_list.setAdapter(new ServiceDistrictAdapter(list));
        mTv_totalCount.setText(String.format(getResources().getString(R.string.nearby_total_district_count),list.size()));
        initMapView(list);
        LocationService.getInstance().clearLastLocationInfo();
    }

    private void showUI(boolean isSearching){
        mMapView.setVisibility(isSearching ? View.GONE : View.VISIBLE);
        mRv_list.setVisibility(isSearching ? View.GONE : View.VISIBLE);
        mTv_totalCount.setVisibility((isSearching ? View.GONE :View.VISIBLE));
        mTv_seaching_notify.setVisibility(isSearching ? View.VISIBLE : View.GONE);
    }

    @OnClick({R.id.tv_searching_notify,R.id.tv_search})
    public void doReSearchWhenFail(TextView view){
        switch (view.getId()){
            case R.id.tv_searching_notify:
                getCurrentServiceDistrict();
                break;
            case R.id.tv_search:
                startTargetActivity(SearchDistrictAreaActivity.class);
                break;
            default:
                break;
        }

    }


    /**
     * 地图显示服务区列表
     */
    private void initMapView(ArrayList<ServiceDistrictItem> list){

        if(mBaiduMap == null) {
            mBaiduMap = mMapView.getMap();
        }else {
            mBaiduMap.clear();
        }


        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        if(list != null && list.size() > 0){

            LatLng CurrentPoint = new LatLng(locInfo.getLatitude(),locInfo.getLongitude());
            ArrayList<OverlayOptions> overlayOptionsArrayList = new ArrayList<>();
//
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_location_marker);

            BitmapDescriptor bitmapAutoEnter = BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_current_district_marker);


            OverlayOptions CurrentPositionOption = new MarkerOptions()
                    .position(CurrentPoint)
                    .icon( BitmapDescriptorFactory
                            .fromResource(R.drawable.ic_current_location));

            for(ServiceDistrictItem item : list){
                double longtitude = item.longitude;
                double latitude = item.latitude;
                LatLng serviceDistrictPoint = new LatLng(latitude,longtitude);
                BitmapDescriptor ic_img = bitmap;
                if(item.distance <= autoEnterDistance){
                    ic_img = bitmapAutoEnter;
                }
                OverlayOptions option = new MarkerOptions()
                        .position(serviceDistrictPoint)
                        .icon(ic_img);

                overlayOptionsArrayList.add(option);
            }

            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(CurrentPoint)
                    .zoom(8)
                    .build();

            mBaiduMap.addOverlays(overlayOptionsArrayList);
            mBaiduMap.addOverlay(CurrentPositionOption);

            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mBaiduMap.setMapStatus(mMapStatusUpdate);

        }
    }

    /**
     * 附近服务区列表
     */
    public class ServiceDistrictAdapter extends  RecyclerView.Adapter<ServiceDistrictAdapter.DistrictViewHolder>{

        public ArrayList<ServiceDistrictItem> mDataList = new ArrayList<>();

        public ServiceDistrictAdapter (ArrayList<ServiceDistrictItem> list){
            mDataList = list;
        }

        @Override
        public ServiceDistrictAdapter.DistrictViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View mView = LayoutInflater.from(ServiceDistrictListActivity.this).inflate(R.layout.service_district_list_item, parent, false);
            return new DistrictViewHolder(mView);
        }

        @Override
        public void onBindViewHolder(ServiceDistrictAdapter.DistrictViewHolder _holder, int position) {
            final ServiceDistrictItem item = mDataList.get(position);
            final DistrictViewHolder holder = _holder;


            holder.mTv_district_name.setText(item.serviceName);
            StringBuilder highWayNameAndDirection = new StringBuilder(item.expressWayName);
            highWayNameAndDirection.append(" --- ").append(item.direction);
            holder.mTv_highway_name.setText(highWayNameAndDirection.toString());
//            holder.mTv_direction.setText(item.direction);
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(item.imageUrl)
                    .asBitmap()
                    .placeholder(R.drawable.default_img)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(holder.mIv_img);

            if(item.distance <= autoEnterDistance){
                Drawable drawable= getResources().getDrawable(R.drawable.ic_selected_district);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.mTv_distance.setCompoundDrawables(drawable,null,null,null);
                holder.mTv_distance.setCompoundDrawablePadding(DisplayUtil.dip2px(ServiceDistrictListActivity.this,5));
                holder.mTv_distance.setTextSize(TypedValue.COMPLEX_UNIT_DIP,14);
                holder.mTv_distance.setText(R.string.current_location);
            }else {
                holder.mTv_distance.setTextSize(TypedValue.COMPLEX_UNIT_DIP,12);
                holder.mTv_distance.setText(String.valueOf(item.distance) + getString(R.string.distance_unit));
                holder.mTv_distance.setCompoundDrawables(null,null,null,null);
            }


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DistrictDetailActivity.launch(ServiceDistrictListActivity.this,item);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }

        class DistrictViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.tv_district_name) TextView mTv_district_name;
            @Bind(R.id.tv_express_way_name) TextView mTv_highway_name;
            @Bind(R.id.tv_distance) TextView mTv_distance;
            @Bind(R.id.iv_district_img)
            ImageView mIv_img;
//            @Bind(R.id.tv_direction) TextView mTv_direction;


            public DistrictViewHolder(View itemView){
                super(itemView);
                ButterKnife.bind(this,itemView);
            }

        }
    }

    @Override
    public void onResume(){
        super.onResume();
        if(mMapView != null) {
            mMapView.onResume();
        }
    }


    @Override
    public void onDestroy(){
        super.onDestroy();
        if(mMapView != null) {
            mMapView.onDestroy();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mMapView != null) {
            mMapView.onPause();
        }
    }


}
